<?php
/**
 * Created by JieHuiLong.
 * E-mail: jiehuilong@icloud.com
 * Date: 2016/8/16
 * Time: 16:00
 * 广告分组管理控制器
 */

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Http\Requests\DomainAttrCreateRequest;
use App\Http\Requests\DomainAttrUpdateRequest;
use App\Models\DomainAttributes as DomainAttr;
use App\Models\Domain;
use App\Models\Group;
use App\Models\AdminUser as User;
use App\Models\Templates;
use Cache;
use DB;

class DomainAttrController extends Controller
{
    protected $fields = [
        'uid' => '',
        'username' => '',
        'did' => '',
        'domain' => '',
        'type' => '',
        'type_value' => '',
        'name' => '',
        'value' => '',
        'call_tag' => '',
    ];

    public function __construct(Request $request)
    {
        $this->did = $request->get('did')?$request->get('did'):0;
        if( $this->did != 0 ){
            $this->domainName =Domain::where('id', $this->did )->value('domain');
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = array();
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $did =  $request->get('did');
            $didCondition =$did ? [['did', '=',$did],]:[['did', '>',0],];

            $data['recordsTotal'] = DomainAttr::where(session('authAdminCondition'))->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = DomainAttr::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('value', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->where($didCondition)->count();

                $data['data'] = DomainAttr::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('value', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->where($didCondition)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                //$data['recordsFiltered'] = DomainAttr::where($didCondition)->count();
				$data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = DomainAttr::where(session('authAdminCondition'))->where($didCondition)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        if( $this->did != 0 ){
            $data['domainId'] = $this->did;
            $data['domainName'] = $this->domainName;
        }
        return view('admin.domainAttr.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request )
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $userList = User::lists('name', 'id');
        $data['domainList'] = Domain::select('id', 'domain', 'uid', 'username', 'gid', 'gname')->get();
        $data['did'] = $this->did;
        if( $this->did != 0 ){
            $data['domainId'] = $this->did;
            $data['domainName'] = $this->domainName;
        }
        foreach ($data['domainList'] as $key => $obj) {
            if ($obj->id == $data['did']) {
                $data['domainList'][$key] = $data['domainList'][0];
                $data['domainList'][0] = $obj;
            }
        }
        if (count($data['domainList']) > 0) {
            return view('admin.domainAttr.create', $data);
        } else {
            return redirect('/admin/domain/create');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(DomainAttrCreateRequest $request)
    {
        $domainAttr = new DomainAttr();
        foreach (array_keys($this->fields) as $field) {
            $domainAttr->$field = trim($request->get($field));
        }
        $id = DomainAttr::where(["did"=>$domainAttr->did,"call_tag"=>$domainAttr->call_tag])->value('id');
        if($id){
            return back()->withErrors('添加失败！【调用标签】不能重复，请您使用其他标签名');
        }else{
            $domainAttr->save();
			$userToken = Cache::rememberForever('userToken', function () {
				$tokenUid = auth()->user()->id;
				$token = DB::table('tokens');
				$userToken = $token->where('uid', '=', $tokenUid)->value('token');
				if ($userToken === null) {
					$userToken = $this->createToken($tokenUid);
				}
				return $userToken;
			});
			$domain = Domain::find($domainAttr->did);
			$this->crossUpTpl2($domainAttr->did,$domain->tpl_id,$userToken);
			event(new \App\Events\userActionEvent('\App\Models\DomainAttr',$domainAttr->id, 1, '添加域名调用标签['.$domainAttr->name.']' ));
            return redirect('/admin/domainAttr?did='.$domainAttr->did)->withSuccess('添加成功！');
        }
        /*$domainAttr->save();
        return redirect('/admin/domainAttr?did='.$domainAttr->did)->withSuccess('添加成功！');*/
        //return redirect('/admin/domainAttr')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $domainAttr = DomainAttr::find((int)$id);
        if (!$domainAttr) return redirect('/admin/domainAttr')->withErrors("找不到该属性!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $domainAttr->$field);
        }
        $data['id'] = (int)$id;
        $data['domainId'] = $domainAttr->did;
        $data['domainName'] = $domainAttr->domain;

        $data['domainList'] = Domain::select('id', 'domain', 'uid', 'username')->get();
        return view('admin.domainAttr.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(DomainAttrUpdateRequest $request, $id)
    {
        $domainAttr = DomainAttr::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $domainAttr->$field = trim($request->get($field));
        }
        $id = DomainAttr::where(["did"=>$domainAttr->did,"call_tag"=>$domainAttr->call_tag])->value('id');
        if($id && $domainAttr->call_tag !=$domainAttr->call_tag){
            return back()->withErrors('添加失败！【调用标签】不能重复，请您使用其他标签名');
        }else{
            $domainAttr->save();
			$userToken = Cache::rememberForever('userToken', function () {
				$tokenUid = auth()->user()->id;
				$token = DB::table('tokens');
				$userToken = $token->where('uid', '=', $tokenUid)->value('token');
				if ($userToken === null) {
					$userToken = $this->createToken($tokenUid);
				}
				return $userToken;
			});
			$domain = Domain::find($domainAttr->did);
			$this->crossUpTpl2($domainAttr->did,$domain->tpl_id,$userToken);
			event(new \App\Events\userActionEvent('\App\Models\DomainAttr',$id, 3, '更新域名调用标签['.$domainAttr->name.']'));
            return redirect('/admin/domainAttr?did='.$domainAttr->did)->withSuccess('添加成功！');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = DomainAttr::find((int)$id);
            if ($tag) {
				$did=$tag->did;
				$name = $tag->name;
                $tag->delete();
				$userToken = Cache::rememberForever('userToken', function () {
					$tokenUid = auth()->user()->id;
					$token = DB::table('tokens');
					$userToken = $token->where('uid', '=', $tokenUid)->value('token');
					if ($userToken === null) {
						$userToken = $this->createToken($tokenUid);
					}
					return $userToken;
				});
				$domain = Domain::find($did);
				$this->crossUpTpl2($did,$domain->tpl_id,$userToken);
				event(new \App\Events\userActionEvent('\App\Models\DomainAttr',$id, 2, '删除域名调用标签['.$name.']'));
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
			foreach($idArr as $ids){
				$userToken = Cache::rememberForever('userToken', function () {
					$tokenUid = auth()->user()->id;
					$token = DB::table('tokens');
					$userToken = $token->where('uid', '=', $tokenUid)->value('token');
					if ($userToken === null) {
						$userToken = $this->createToken($tokenUid);
					}
					return $userToken;
				});
				$domain = Domain::find($ids);
				$this->crossUpTpl2($ids,$domain->tpl_id,$userToken);
			}
			$names = '';
			$ds = DomainAttr::whereIn('id',$idArr)->get();
			foreach($ds as $d){ $names.=$d->name."";}
            $recordRow =DomainAttr::whereIn('id',$idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\DomainAttr',0, 2, '删除域名调用标签['.$names.']'));
            if(!$recordRow){
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	public function crossUpTpl2($id,$tpl_id,$userToken){
        //获取域名信息
        $domain = Domain::find((int)$id);
        //获取域名属性
        $listsAttr = DomainAttr::where('did', $id)->get();
        $dataAttr = [];
        foreach ($listsAttr as $rowKey => $row) {
            $dataAttr[$row['call_tag']] = $row['value'];
        }
        //读取推广模板信息
        $sourceCode = htmlentities(Templates::where('id', $tpl_id)->value('source_code'));
        $sourceCode = $this->replaceTpLable($dataAttr, $sourceCode);
        //读取审核模板信息
        $sh_tpl_id = Group::where('id', $domain->gid)->value('sh_tpl_id');
        $sourceCodeCompany = htmlentities(Templates::where('id', $sh_tpl_id)->value('source_code'));
        $sourceCodeCompany = $this->replaceTpLable($dataAttr, $sourceCodeCompany);
        //把最新的模板保存到数据中
        $data['uid'] = $domain->uid;
        $data['username'] = $domain->username;
        $data['did'] = $domain->id;
        $data['gid'] = $domain->gid;
        $data['domain'] = $domain->domain;
        $data['html'] = $sourceCode;
        $time = time();
		$data['token'] = md5($userToken . $time);
        $newSkins = DB::table('new_skins');

        $newSkins->where('did', $domain->id)->delete();
        //保存推广模板
        $newSkins->insert($data);
        //保存审核模板
        $data['html'] = $sourceCodeCompany;
        $data['token'] = md5($data['token'] . $data['did']);
        $newSkins->insert($data);

        $data['directory']= $domain->directory;
        $url =  $domain->access_type.'://'.$domain->domain;
        $url .= "/upgrade.php";
		$data['time'] =$time;
		if(httpcode($url)==200){
			return $this->curlPost($url,$data);
		}else{
			return "error";
		}
	}
	public function curlPost($url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	 protected function replaceTpLable($dataAttr, $sourceCode)
    {
        //循环替换模板标签属性
        foreach ($dataAttr as $key => $value) {
            $sourceCode = str_replace("{{" . $key . "}}", $value, $sourceCode);
        }
        $sourceCode = str_replace('{{$', "<?php echo \$data['", $sourceCode);
        $sourceCode = str_replace('$}}', "'];?>", $sourceCode);
        //清空不存在的值
        $sourceCode = preg_replace("/{{(.*?)}}/", '', $sourceCode);
        $sourceCode = html_entity_decode($sourceCode);
        return $sourceCode;
    }
}